from django.utils.deprecation import MiddlewareMixin
from django.http import JsonResponse   

from utils.jwttools import verify_token



class MyMiddleware(MiddlewareMixin):
    def process_request(self, request):
        """
        请求中判断
        1. 判断请求的路由是不是register/login
        2. 是就放行
        3.不是就判断请求头中是否携带token，携带token，就验证，没问题放行，有问题就报错
        """
        if request.path in ['/register/', '/login/','/sms_code/','/phone_login/','/template_list/','/user_info/']:
            return
        else:
            # 获取token
            token = request.META.get('HTTP_AUTHORIZATION')
            if not token:
                return JsonResponse({'code': 401, 'msg': '请先登录'})
            else:
                # 验证token
                rest, status = verify_token(token)
                print("rest>>>", rest, status)
                if status:
                    return JsonResponse({'code': 401, 'msg': rest})
                else:
                    request.user = rest.get('username')
                    return
